var selectedStatRow = '';
var queryFlag = false;
var queryFlagLine = false;
var reQueryTime=1*1000, queryTime, queryTimeLine;
var echartLine, echartPie;
var statDate= '';
var selected_seed_id;
var selected_biz_id;

$(function () {
    initDateWithRange('#statEndTime', null, defStatEndTime);
    statDate = defStatEndTime;
    //初始化左侧表格树
    initLeftTree(countData);
    /*$('#dataTable').bootstrapTable({
        class: 'table table-striped table-hover',
        url: basePath + 'pvuv/pvuvStat/pageFindPVUVData?t=' + new Date().getTime(),
        queryParams:getStatParams,
        pagination: false,//分页请设置为false
        treeView: true,//是否开启树视图
        treeId: "id",//id字段
        treeField: "name",//展示树的字段
        striped:true,
        columns: [
            {field: 'id', title: 'id',visible:false},
            {field: 'parentId', title: 'parentId',visible:false},
            {field: 'seedType', title: 'seedType',visible:false},
            {field: 'seedId', title: 'seedId',visible:false},
            {field: 'bizId', title: 'bizId',visible:false},
            {field: 'name', title: '统计项',width:'200px', formatter:'initCheck'},
            {field: 'countNum', title: countType ,width:'100px'}
        ]
    });*/
    if (initEChartsLineData) {
        createEChartLine(initEChartsLineData);
    }
});

function initLeftTree(dd) {
    var options = {
        data : dd,
        showTags: true,
    };
    $('#dataTable').treeview(options);
    $('#dataTable').on('nodeSelected', function (event, data) {
        selectedStatRow = data;
        selected_seed_id = data.seedId;
        selected_biz_id = data.bizId;
        if (data.leafNode == 'N') {
            $('#_pieDiv').removeClass('noShow');
        } else {
            $('#_pieDiv').addClass('noShow');
        }
        doRefreshCline(data);
    });
}

/*function initExpand(value, row, index) {
    if (row.id == selected_left_parentId) {
        $('#dataTable').bootstrapTable("expandNode", row.id);
    }
    return value;
}*/
/*
function initCheck(value, row, index) {
    if (!selected_left_id) {
        return value;
    }
    if (row.id == selected_left_id) {
        setTimeout(function(){
            $("#dataTable > tbody > tr[data-index='" +index+"']").addClass("success");
        }, 200);
        selectedStatRow = row;
        doRefreshCline();
    }
    return value;
}*/

function getStatParams() {
    var statEndTime = $('#statEndTime').val();
    var bizType = $('#bizType').val();
    var seedType = $('#seedType').val();
    var source = $('#source').val();
    return {
        statEndTime : statEndTime,
        bizType : bizType,
        source : source,
        seedType : seedType,
        countType : countType,
        queryFlag : queryFlag
    };
}

function doRefresh() {
    /*// selectedStatRow = '';
    /!*$('#dataTable').bootstrapTable('refresh', {
        url: basePath + 'pvuv/pvuvStat/pageFindPVUVData?t=' + new Date().getTime()
    });*!/
    // if (!selectedStatRow) {
        /!*if (initEChartsLineData) {
            initEChartsLineData.xNames = getXNames();
            createEChartLine(initEChartsLineData);
        }*!/
        // $('#_pieDiv').addClass('noShow');
    // }*/
    var statEndTime = $('#statEndTime').val();
    var bizType = $('#bizType').val();
    var seedType = $('#seedType').val();
    var source = $('#source').val();
    var postData = {
        statEndTime : statEndTime,
        bizType : bizType,
        source : source,
        seedType : seedType,
        countType : countType,
        // queryFlag : queryFlag,
        selectedSeedId : selected_seed_id,
        selectedBizId : selected_biz_id,
    };
    // showLoading();
    // queryFlag = true;
    $.ajax({
        type: 'post',
        url: basePath + 'pvuv/pvuvStat/pageFindPVUVData?t=' + new Date().getTime(),
        dataType: 'json',
        data: postData,
        success : function (data) {
            // hideLoading();
            if (data) {
                initLeftTree(data);
                if (selectedStatRow) {
                    doRefreshCline(selectedStatRow);
                }
            } else {
                initLeftTree([]);
                if (initEChartsLineData) {
                    initEChartsLineData.xNames = getXNames();
                    createEChartLine(initEChartsLineData);
                }
                $('#_pieDiv').addClass('noShow');
            }
        },
        error: function (request) {
            // hideLoading();
            delayToastr('系统错误');
        }
    });
}

function doRefreshCline(comData) {
    if (!comData) {
        return;
    }
    statDate = $('#statEndTime').val();
    var postData = {
        statEndTime : statDate,
        source : $('#source').val(),
        bizType : $('#bizType').val(),
        seedType : $('#seedType').val(),
        seedId : comData.seedId,
        bizId : comData.bizId,
        isLeaf : comData.leafNode,
        legendName : comData.name,
        countType : countType,
        queryFlag : queryFlagLine
    };
    showLoading();
    queryFlagLine = true;
    $.ajax({
        type: 'post',
        url: basePath + 'pvuv/pvuvStat/getClineData?t=' + new Date().getTime(),
        dataType: 'json',
        data: postData,
        success : function (data) {
            if (!data || !data.result) {
                hideLoading();
                toastr.error(data ? data.message : '获取数据失败');
                return;
            }
            if (!data.content) {
                if (!queryTimeLine) {
                    queryTimeLine = setInterval(function() {
                        if (queryFlagLine) {
                            doRefreshCline(comData);
                        } else {
                            queryFlagLine = false;
                            if(queryTimeLine){
                                clearInterval(queryTimeLine);
                                queryTimeLine = '';
                            }
                        }
                    }, reQueryTime);
                }
                return;
            }
            hideLoading();
            queryFlagLine = false;
            if (queryTimeLine) {
                clearInterval(queryTimeLine);
                queryTimeLine = '';
            }
            if (data.content.errorMsg) {
                toastr.error(data.content.errorMsg);
                return;
            }
            createEChartLine($.parseJSON(data.content.chartLineData));
            if (comData.leafNode == 'N') {
                createEChartPie($.parseJSON(data.content.chartPieData));
            }
        },
        error: function (request) {
            hideLoading();
            delayToastr('系统错误');
        }
    });
}

function createEChartLine(data) {
    var str = countType == 'pv' ? '(PV)' : '(UV)';
    var option = {
        title : {
            text: data.title + str,
            subtext: '统计日期：'+statDate
        },
        tooltip : {
            trigger: 'axis'
        },
        grid:{
            y: 100,
            x2 : 180
        },
        legend: {
            orient : 'vertical',
            x : 'right',
            y: 'center',
            data: data.legendNames,
        },
        toolbox: {
            show: true,
            feature: {
                dataView: {readOnly: true, show: true},
                magicType: {type: ['line', 'bar']},
                restore: {show: true},
                saveAsImage: {show: true}
            },
            right:'9%'
        },
        calculable : true,
        xAxis : [
            {
                type : 'category',
                boundaryGap : false,
                data : data.xNames,
            }
        ],
        yAxis : [
            {
                type : 'value',
            }
        ],
        series : data.series,
    };
    if(echartLine){//防止过度点击
        echartLine.dispose();
    }
    // 图表实例化------------------
    echartLine = echarts.init(document.getElementById('chartLine'),theme);
    //渲染图表
    echartLine.setOption(option);
}

function formatName(list) {
    var resultData = [];
    if (!list) {
        return list;
    }
    for (var i=0; i<list.length; i++) {
        var str = list[i];
        if (str && str.length > 10) {
            str = str.substring(0, 10) + '...';
        }
        resultData.push(str);
    }
    return resultData;
}

function createEChartPie(data) {
    var str = countType == 'pv' ? '(PV)' : '(UV)';
    var option = {
        title : {
            text: data.title + str,
            subtext: '统计日期：'+statDate
        },
        grid:{
            right:'50%',
            top:'25%'
        },
        legend: {
            orient : 'vertical',
            x : 'right',
            y: 'center',
            data: data.legendNames,
        },
        toolbox: {
            show : true,
            feature : {
                mark : {show: true},
                dataView : {show: true, readOnly: false},
                magicType : {
                    show: true,
                    type: [],
                    option: {
                        funnel: {
                            x: '25%',
                            width: '50%',
                            funnelAlign: 'left',
                            max: 1548
                        }
                    }
                },
                restore : {show: true},
                saveAsImage : {show: true}
            },
            right:'9%'
        },
        tooltip : {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        calculable : true,
        series : [
            {
                name:data.title + '分布',
                type:'pie',
                radius : '40%',
                center: ['35%', '50%'],
                data:data.series,
            }
        ]
    };
    if(echartPie){//防止过度点击
        echartPie.dispose();
    }
    // 图表实例化------------------
    echartPie = echarts.init(document.getElementById('chartPie'),theme);
    //渲染图表
    echartPie.setOption(option);
}

function getFormatDate(dateStr, n) {//n为你要传入的参数，当前为0，前一天为1，后一天为-1
    var date = new Date(dateStr);
    var year, month, day;
    date.setDate(date.getDate() - n);
    year = date.getFullYear();
    month = date.getMonth() + 1;
    day = date.getDate();
    // return year + '-' + (month < 10 ? ('0' + month) : month) + '-' + (day < 10 ? ('0' + day) : day);
    return (month < 10 ? ('0' + month) : month) + '.' + (day < 10 ? ('0' + day) : day);
}

function getXNames() {
    var statEndTime = $('#statEndTime').val();
    if (!statEndTime) {
        toastr.error('时间格式错误');
        return;
    }
    var xNames = [];
    for (var i=6; i>=0; i--) {
        xNames.push(getFormatDate(statEndTime, i));
    }
    return xNames;
}